const express = require('express');
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const router = express.Router();

// 创建相册上传目录
const galleryDir = path.join(__dirname, '../public/apps/gallery/uploads');
if (!fs.existsSync(galleryDir)) {
    fs.mkdirSync(galleryDir, { recursive: true });
}

// 临时目录用于存储上传的分片
const tempDir = path.join(__dirname, '../temp');
if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir, { recursive: true });
}

// 配置文件上传
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, tempDir);
    },
    filename: (req, file, cb) => {
        cb(null, Date.now() + '-' + file.originalname);
    }
});
const upload = multer({ storage });

// 获取相册文件列表
router.get('/files', (req, res) => {
    fs.readdir(galleryDir, (err, files) => {
        if (err) {
            return res.status(500).json({ error: '无法读取文件列表' });
        }
        
        const fileList = files.map(file => {
            const filePath = path.join(galleryDir, file);
            const stats = fs.statSync(filePath);
            const ext = path.extname(file).toLowerCase();
            
            // 判断文件类型
            let type = 'other'; // 默认为其他类型
            if (['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'].includes(ext)) {
                type = 'image';
            } else if (['.mp4', '.mov', '.avi', '.mkv', '.webm'].includes(ext)) {
                type = 'video';
            }
            
            return {
                name: file,
                path: `/apps/gallery/uploads/${file}`,
                type: type,
                mimetype: getFileMimeType(ext),
                size: stats.size
            };
        });
        
        res.json(fileList);
    });
});

// 根据扩展名获取 MIME 类型
function getFileMimeType(ext) {
    const mimeTypes = {
        '.jpg': 'image/jpeg',
        '.jpeg': 'image/jpeg',
        '.png': 'image/png',
        '.gif': 'image/gif',
        '.bmp': 'image/bmp',
        '.webp': 'image/webp',
        '.mp4': 'video/mp4',
        '.mov': 'video/quicktime',
        '.avi': 'video/x-msvideo',
        '.mkv': 'video/x-matroska',
        '.webm': 'video/webm'
    };
    return mimeTypes[ext] || 'application/octet-stream';
}

// 上传文件分片
router.post('/upload-chunk', upload.single('chunk'), (req, res) => {
    const { fileId, fileName, chunkIndex, totalChunks } = req.body;
    
    if (!fileId || !fileName || chunkIndex === undefined || !totalChunks) {
        return res.status(400).json({ success: false, error: '缺少必要的参数' });
    }
    
    // 创建临时目录存储该文件的所有分片
    const fileTempDir = path.join(tempDir, fileId);
    if (!fs.existsSync(fileTempDir)) {
        fs.mkdirSync(fileTempDir, { recursive: true });
    }
    
    // 移动分片到临时目录
    const chunkFileName = `chunk-${chunkIndex}`;
    const chunkPath = path.join(fileTempDir, chunkFileName);
    
    fs.rename(req.file.path, chunkPath, (err) => {
        if (err) {
            return res.status(500).json({ success: false, error: '保存分片失败' });
        }
        
        // 检查是否所有分片都已上传完成
        const uploadedChunks = fs.readdirSync(fileTempDir);
        if (uploadedChunks.length == totalChunks) {
            // 合并所有分片
            const finalFilePath = path.join(galleryDir, fileName);
            
            // 按顺序合并分片
            const writeStream = fs.createWriteStream(finalFilePath);
            
            let currentChunk = 0;
            function appendChunk() {
                if (currentChunk >= totalChunks) {
                    // 所有分片已合并完成，清理临时文件
                    fs.rmSync(fileTempDir, { recursive: true, force: true });
                    return res.json({ success: true, message: '文件上传完成' });
                }
                
                const chunkPath = path.join(fileTempDir, `chunk-${currentChunk}`);
                const readStream = fs.createReadStream(chunkPath);
                
                readStream.pipe(writeStream, { end: false });
                readStream.on('end', () => {
                    // 删除已合并的分片
                    fs.unlinkSync(chunkPath);
                    currentChunk++;
                    appendChunk();
                });
                
                readStream.on('error', (err) => {
                    writeStream.close();
                    fs.rmSync(fileTempDir, { recursive: true, force: true });
                    res.status(500).json({ success: false, error: '合并文件失败' });
                });
            }
            
            appendChunk();
        } else {
            res.json({ success: true, message: '分片上传成功' });
        }
    });
});

// 传统上传接口（保留兼容性）
router.post('/upload', upload.array('files'), (req, res) => {
    res.json({ success: true, files: req.files.map(f => f.filename) });
});

// 删除文件
router.delete('/files/:filename', (req, res) => {
    const filePath = path.join(galleryDir, req.params.filename);
    fs.unlink(filePath, (err) => {
        if (err) {
            return res.status(500).json({ error: '删除文件失败' });
        }
        res.json({ success: true });
    });
});

module.exports = router;